﻿using System.Collections;
using System.IO;
using NPOI.SS.UserModel;

namespace MQAMS
{
    public class ScheduleManager
    {
        private readonly string _scheduleFile;
        private readonly ScheduleList _schedules;

        public ScheduleManager(string scheduleFile)
        {
            _scheduleFile = scheduleFile;
            _schedules = new ScheduleList();
            ConvertXls();
        }

        public ScheduleList GetSchedules()
        {
            return _schedules;
        }

        private void ConvertXls()
        {
            using (var fs = new FileStream(_scheduleFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                IWorkbook wb = WorkbookFactory.Create(fs);
                for (int i = 0; i < wb.NumberOfSheets; i++)
                {
                    ISheet sheet = wb.GetSheetAt(i);
                    IEnumerator rows = sheet.GetRowEnumerator();
                    FillSchedules(rows);
                }
            }
        }

        private void FillSchedules(IEnumerator rows)
        {
            if (rows.MoveNext())
            {
                var row = rows.Current as IRow;
                if (row == null) return;

                short lastCellNum = row.LastCellNum;
                //_schedules.EndDate = short.Parse(row.GetCell(lastCellNum - 1).ToString());

                rows.MoveNext();
                while (rows.MoveNext())
                {
                    var schedule = new Schedule();
                    row = rows.Current as IRow;
                    if (row == null) return;

                    schedule.Name = row.GetCell(2).ToString();
                    if (!string.IsNullOrEmpty(schedule.Name.Trim()))
                    {
                        for (int i = 3; i < lastCellNum; i++)
                        {
                            string cell = row.GetCell(i).ToString().Trim();
                            schedule.WorkTimes.Add(ConvertWorkTime(cell));
                        }
                        _schedules.Schedules.Add(schedule);
                    }
                }
            }
        }

        private WorkTime ConvertWorkTime(string workTime)
        {
            var ret = WorkTime.Nd;

            switch (workTime)
            {
                case "上班":
                    ret = WorkTime.AllDay;
                    break;
                case "上午休":
                    ret = WorkTime.Pm;
                    break;
                case "下午休":
                    ret = WorkTime.Am;
                    break;
                case "休息":
                    ret = WorkTime.None;
                    break;
            }

            return ret;
        }
    }
}